package cn.pconline.autoclub.web.cms;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.ClubStat;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaIndex;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.Subject;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ActivityService;
import cn.pconline.autoclub.service.AlbumService;
import cn.pconline.autoclub.service.ClubLevelService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.CommentService;
import cn.pconline.autoclub.service.DynaIndexService;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.PetrolService;
import cn.pconline.autoclub.service.StatService;
import cn.pconline.autoclub.service.SubjectDynaService;
import cn.pconline.autoclub.service.SubjectService;
import cn.pconline.autoclub.service.TopicService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.WhoisUtil;
import cn.pconline.autoclub.util.app.AppControllerStatic;
import cn.pconline.whoisfront.message.Area;
import cn.pconline.whoisfront.publisher.IpService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author zhouruxuan
 * @date 2014年11月18日 下午4:23:07
 */
@Controller
public class CmsController {

    @Autowired
    private UserService userService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ClubLevelService clubLevelService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private AlbumService albumService;
    @Autowired
    private TopicService topicService;
    @Autowired
    private PetrolService petrolService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private DynaService dynaService;
    @Autowired
    private StatService statService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private SubjectDynaService subjectDynaService;
    @Autowired
    private DynaIndexService dynaIndexService;
    
    private static final Logger log = LoggerFactory.getLogger(CmsController.class);
    private static final int NUM_ARROUND_MYCLUB = 2;//用户车友会的前后两个名

    /**
     * 根据登录用户ID，获取此用户加入的车友会的前后两名车友会列表 按活跃度进行排序
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/cms/club/listNearbyClub.do", method = RequestMethod.GET)
    public void listNearbyClub(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        long userId = WebUtils.paramLong(request, "userId", 0L);

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        //用户不在在
        User user = userService.findUser(userId);
        if (user == null) {
            AppControllerStatic.printErrorMsg(response, "非法参数userId！", jsonObject, callback, AppControllerStatic.V1_VERSION);
            return;
        }
        //没有加入车友会
        ClubMember clubMember = memberService.findClubMemberByUserId(userId);
        Club myClub;
        if (clubMember == null) {
            AppControllerStatic.printErrorMsg(response, "此用户没有加入任何车友会！", jsonObject, callback, AppControllerStatic.V1_VERSION);
            return;
        } else {
            myClub = clubService.getValidClub(clubMember.getClubId());
        }
        //加入的车友会失效
        if (myClub == null) {
            AppControllerStatic.printErrorMsg(response, "此用户没有加入车友会已失效！", jsonObject, callback, AppControllerStatic.V1_VERSION);
        } else {
            int myClubRank = myClub.getRank();
            //前2名车友会
            int beginClub = myClubRank - NUM_ARROUND_MYCLUB <= 0 ? 1 : myClubRank - NUM_ARROUND_MYCLUB;
            //后两名车友会
            int endClub = myClubRank + NUM_ARROUND_MYCLUB;
            List<Club> listClubs = clubService.listNearClubByCountory(beginClub, endClub);
            if (!listClubs.isEmpty()) {
                for (Club club : listClubs) {
                    JSONObject json = new JSONObject();
                    json.put("clubId", club.getClubId());
                    json.put("rank", club.getRank());
                    json.put("clubName", club.getName());
                    json.put("clubUrl", systemConfig.getRoot() + "/" + club.getClubUrl() + "/");
                    //判断是否为登录用户的车友会 1:是，0：不是
                    json.put("isMyClub", club.getClubId() == myClub.getClubId() ? 1 : 0);
                    jsonArray.add(json);
                }
            }
            jsonObject.put("data", jsonArray);
            AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION);
        }
    }

    /**
     * 根据登录用户ID，获取此用户加入的车友会的前后两名车友会列表 按活跃度进行排序 增加活跃度露出
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/cms/2.0/club/listNearbyClub.do", method = RequestMethod.GET)
    public void listRankbyClub(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        long userId = WebUtils.paramLong(request, "userId", 0L);

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        //用户不在在
        User user = userService.findUser(userId);
        if (user == null) {
            AppControllerStatic.printErrorMsg(response, "非法参数userId！", jsonObject, callback, AppControllerStatic.V2_VERSION_LATEST);
            return;
        }
        //没有加入车友会
        ClubMember clubMember = memberService.findClubMemberByUserId(userId);
        Club myClub;
        if (clubMember == null) {
            AppControllerStatic.printErrorMsg(response, "此用户没有加入任何车友会！", jsonObject, callback, AppControllerStatic.V2_VERSION_LATEST);
            return;
        } else {
            myClub = clubService.getValidClub(clubMember.getClubId());
        }
        //加入的车友会失效
        if (myClub == null) {
            AppControllerStatic.printErrorMsg(response, "此用户没有加入车友会已失效！", jsonObject, callback, AppControllerStatic.V2_VERSION_LATEST);
        } else {
            int myClubRank = myClub.getRank();
            //前2名车友会
            int beginClub = myClubRank - NUM_ARROUND_MYCLUB <= 0 ? 1 : myClubRank - NUM_ARROUND_MYCLUB;
            //后两名车友会
            int endClub = myClubRank + NUM_ARROUND_MYCLUB;
            List<Map<String, Object>> listClubs = clubService.listNearByClub(beginClub, endClub);
            if (!listClubs.isEmpty()) {
                for (Map<String, Object> clubMap : listClubs) {
                    JSONObject json = new JSONObject();
                    json.put("clubId", clubMap.get("club_id"));
                    json.put("rank", clubMap.get("rank"));
                    json.put("clubName", clubMap.get("name"));
                    json.put("clubUrl", systemConfig.getRoot() + "/" + clubMap.get("club_url") + "/");
                    //判断是否为登录用户的车友会 1:是，0：不是
                    json.put("isMyClub", Long.parseLong(clubMap.get("club_id").toString()) == myClub.getClubId() ? 1 : 0);
                    //增加活跃度
                    json.put("rankPetrol", clubMap.get("rank_petrol"));
                    jsonArray.add(json);
                }
            }
            jsonObject.put("data", jsonArray);
            AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V2_VERSION_LATEST);
        }
    }

    /**
     * 推荐同城车友会 根据活跃度进行排名，前5位 如果cityId找不到车友会，就根据provinceId进行查询
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/cms/club/listTop5Club.do", method = RequestMethod.GET)
    public void listTop5Club(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        long provinceId = WebUtils.paramLong(request, "provinceId", 0L);
        long cityId = WebUtils.paramLong(request, "cityId", 0L);

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        //provinceId为必传参数
        if (provinceId == 0L) {
            AppControllerStatic.printErrorMsg(response, "参数provinceId不正确！", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        //根据省市ID获取前5名车友会列表
        Pager<Club> pager = clubService.listClubByCityId(cityId, provinceId, 1, 5);
        if (pager == null || pager.getResultList().isEmpty()) {
            //如果市ID没有相关同城车友会，根据省ID获取前5名车友会列表
            pager = clubService.listClubByCityId(0L, provinceId, 1, 5);

        }
        if (pager != null && !(pager.getResultList().isEmpty())) {
            for (Club club : pager.getResultList()) {
                JSONObject json = new JSONObject();
                json.put("clubId", club.getClubId());
                json.put("clubName", club.getName());
                json.put("clubUrl", systemConfig.getRoot() + "/" + club.getClubUrl() + "/");
                jsonArray.add(json);
            }
        }

        jsonObject.put("data", jsonArray);
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
    }

    /**
     *
     * 获取车友会列表接口(APP)
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/cms/1.0/club/getClubByCityOrRegionId.do", method = RequestMethod.GET)
    public void getClubByCityOrRegionId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        WebUtils.setEncoding(req, resp);
        // app签到用这个接口判断，app的调用不能加缓存
        if (!"utf-8".equalsIgnoreCase(req.getParameter("resp_enc"))) {
            WebUtils.setCacheHeader(resp, 3600);//缓存 1h
        }
        String callback = WebUtils.param(req, "callback", "");
        int cityId = WebUtils.paramInt(req, "cityId", 0);
        int provinceId = WebUtils.paramInt(req, "provinceId", 0);
        long seriesId = WebUtils.paramInt(req, "seriesId", 0);
        String[] seriesIds = WebUtils.paramTrim(req, "seriesIds", "").split(",");
        String clubName = WebUtils.paramTrim(req, "clubName", "");
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        long brandId = WebUtils.paramInt(req, "brand", 0);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20, 1, 100);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
        int tabId = WebUtils.paramInt(req, "tagId", 0);//主题ID
        List<Object> sids = new ArrayList<Object>(seriesIds.length);
        if (seriesId > 0) {
            sids.add(seriesId);
        } else {
            for (String s : seriesIds) {
                try {
                    int i = Integer.parseInt(s);
                    if (i > 0) {
                        sids.add(i);
                    }
                } catch (java.lang.NumberFormatException e) {
                    continue;
                }
            }
        }
        //省、市ID判断,直辖市会省市id会一样
        if (provinceId > 0 && cityId > 0 && provinceId == cityId) {
            IpService ipService = IpService.getInstance();
            Area city = ipService.getAreaByCode(cityId);
            if (city == null || city.getAreaLevel() != 2) {
                cityId = 0;
            }
        }
        Pager<Club> pager = clubService.pageClubByPlaceId(cityId, 0, provinceId, brandId, sids.toArray(), clubId, clubName, pageNo, pageSize, tabId);
        JSONObject json = new JSONObject();
        if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            JSONArray jsonArray = new JSONArray();
            for (Club club : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("clubId", club.getClubId());
                jsonObject.put("clubStatus", club.getStatus());
                jsonObject.put("name", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
                jsonObject.put("logo", EncodeUtils.encodeForHTML(club.getLogo(), sourceAgent));
                jsonObject.put("memberSum", club.getMemberNum());
                jsonObject.put("vipSum", club.getVipNum());
                jsonObject.put("totalPetrol", petrolService.getValidPetrol(club.getClubId()).getTotalPetrol());
                jsonObject.put("level", club.getLevelId());

                jsonObject.put("rank", club.getRank());
                jsonObject.put("regionRank", club.getRegionRank());
                jsonObject.put("provinceRank", club.getProvinceRank());
                jsonObject.put("brandRank", club.getBrandRank());
                jsonObject.put("brandId", club.getBrandId());
                jsonObject.put("brandName", EncodeUtils.encodeForHTML(club.getBrandName(), sourceAgent));
                jsonObject.put("seriesName", EncodeUtils.encodeForHTML(club.getSeriesName(), sourceAgent));

                jsonObject.put("provinceName", EncodeUtils.encodeForHTML(club.getProvinceName(), sourceAgent));
                jsonObject.put("cityName", EncodeUtils.encodeForHTML(club.getCityName(), sourceAgent));

                jsonObject.put("introduce", EncodeUtils.encodeForHTML(club.getIntroduce(), sourceAgent));
                jsonObject.put("qqGroup", club.getQqGroup());
                jsonObject.put("clubUrl", club.getClubUrl());

                jsonArray.add(jsonObject);
            }
            AppUtils.setSuccessCode(json);
            json.put("data", jsonArray);
            json.put("total", pager.getTotal());
            json.put("pageNo", pager.getPageNo());
            json.put("pageCount", pager.getPageCount());
            json.put("pageSize", pager.getPageSize());
        } else {
            json.put("data", new JSONArray());
            AppUtils.setSuccessCode(json);
        }
        json.put("version", 1.0);

        try {
            PrintWriter print = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                print.println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toJSONString() + ")");
            } else {
                print.println(json.toJSONString());
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            log.error("error", ex);
        }
    }
    private static final int DEF_CLUBS_NUM = 5;//默认返回5个车友会
    private static final int DEF_TONGCHENG_CLUBS_NUM = 4;//默认返回4个同城车友会

    /**
     * 汽车网车友会报价库露出接口 排名即是指“活跃度” 1.默认出当前车系的车友会，按照排名先后露出，最多5个
     * 2.当前车系不足5个的，补当前品牌的车友会，最多5个，车系的优先排前面，品牌的排后面
     * 3.当前品牌不足5个车友会的时候（至少还有1个），下面会出现推荐车友会，缺几个就补几个，最多露出5个
     * 4.推荐车友会的露出，以IP作为识别，按地区排名最前的来露出，优先城市，然后是省份，最后是全国
     * 5.如果品牌下面一个车友会也没有，则顶部露出创建车友会的按钮 6.下面出该地区下面排名最前的4个地区车友会
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/cms/1.0/club/listTopClubs.do", method = RequestMethod.GET)
    public void listTopClubs(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //缓存1小时
        WebUtils.setCacheHeader(response, 3600);
        //获取相关参数
        String callback = WebUtils.param(request, AppControllerStatic.APP_API_PARA_CALLBACK, "");
        int xssEncode = WebUtils.paramInt(request, AppControllerStatic.APP_API_PARA_XSSENCODE, 0);
        long brandId = WebUtils.paramInt(request, AppControllerStatic.APP_API_PARA_BRANDID, 0);
        long seriesId = WebUtils.paramInt(request, AppControllerStatic.APP_API_PARA_SERIESID, 0);
        String ip = WebUtils.param(request, "ip", "");

        JSONObject jsonObject = new JSONObject();

        //非空参数检查
        if (seriesId == 0) {
            AppControllerStatic.printErrorMsg(response, "非法参数seriesId", jsonObject, callback, AppControllerStatic.V1_VERSION);
            return;
        }
        if (brandId == 0) {
            AppControllerStatic.printErrorMsg(response, "非法参数brandId", jsonObject, callback, AppControllerStatic.V1_VERSION);
            return;
        }

        //获取省市ID
        if (StringUtils.isBlank(ip)) {
            AppControllerStatic.printErrorMsg(response, "非法参数ip", jsonObject, callback, AppControllerStatic.V1_VERSION);
            return;
        }
        JSONObject region;
        try {
            region = WhoisUtil.getProvinceAndCity(ip);
        } catch (Exception exception) {
            AppControllerStatic.printErrorMsg(response, "ip地址不正确", jsonObject, callback, AppControllerStatic.V1_VERSION);
            return;
        }
        long provinceId = region.get("areaCode").toString().equals("null") ? 0 : region.getIntValue("areaCode");
        long cityId = region.get("cityCode").toString().equals("null") ? 0 : region.getIntValue("cityCode");

        //返回的车友会列表
        List<Club> returnClubs = new ArrayList<Club>();
        //返回推荐车友会列表
        List<Club> isRecommendClubs = new ArrayList<Club>();
        //根据车系查找车友会，按照排名先后露出，最多5个
        List<Club> seriesClubs = clubService.getListBySeriesId(seriesId, 1, DEF_CLUBS_NUM);
        returnClubs.addAll(seriesClubs);
        //如果根据车系查找的车友会不足5个，查找当前品牌下的车友会
        if (returnClubs.isEmpty() || returnClubs.size() < DEF_CLUBS_NUM) {
            List<Club> brandClubs = clubService.listClubByBrandIdExceptSeriesId(brandId, seriesId, 1, DEF_CLUBS_NUM - returnClubs.size());
            returnClubs.addAll(brandClubs);
        }

        //1:有品牌车友会；0：没有品牌车友会
        int isBrandclub = 1;

        //如果品牌没有车友会，显示4个同城车友会
        if (returnClubs.isEmpty()) {
            isBrandclub = 0;
            //查找当前同城车友会
            List<Club> cityClubs = clubService.getListByCityIdProvinceId(cityId, provinceId, 1, DEF_TONGCHENG_CLUBS_NUM);
            returnClubs.addAll(cityClubs);
            //查找当前同省车友会
            if (returnClubs.size() < DEF_TONGCHENG_CLUBS_NUM) {
                List<Club> proviceClubs = clubService.listClubByProvinceIdExceptCityId(provinceId, cityId, 1, DEF_TONGCHENG_CLUBS_NUM - returnClubs.size());
                returnClubs.addAll(proviceClubs);
            }
            //查找全国车友会
            if (returnClubs.size() < DEF_TONGCHENG_CLUBS_NUM) {
                List<Club> countryClubs = clubService.getListByCityIdProvinceId(0, 0, 1, DEF_TONGCHENG_CLUBS_NUM - returnClubs.size());
                returnClubs.addAll(countryClubs);
            }

        } else if (returnClubs.size() < DEF_CLUBS_NUM) {//设置品牌车友会和推荐车友会
            //查找当前同城车友会
            List<Club> cityClubs = clubService.getListByCityIdProvinceId(cityId, provinceId, 1, DEF_CLUBS_NUM - returnClubs.size());
            isRecommendClubs.addAll(cityClubs);
            //查找当前同省车友会
            int totalSize = returnClubs.size() + isRecommendClubs.size();
            if (totalSize < DEF_CLUBS_NUM) {
                List<Club> proviceClubs = clubService.listClubByProvinceIdExceptCityId(provinceId, cityId, 1, DEF_CLUBS_NUM - totalSize);
                isRecommendClubs.addAll(proviceClubs);
            }
            //查找全国车友会
            totalSize = returnClubs.size() + isRecommendClubs.size();
            if (totalSize < DEF_CLUBS_NUM) {
                List<Club> countryClubs = clubService.getListByCityIdProvinceId(0, 0, 1, DEF_CLUBS_NUM - totalSize);
                isRecommendClubs.addAll(countryClubs);
            }
        }

        //组装品牌车友会属性列表
        JSONArray jsonArray = new JSONArray();
        for (Club club : returnClubs) {
            JSONObject json = new JSONObject();
            json.put("clubId", club.getClubId());
            json.put("name", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getName()) : club.getName());
            json.put("logo", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getLogo()) : club.getLogo());
            json.put("url", systemConfig.getRoot() + "/" + club.getClubUrl() + "/");
            //会员数
            int count = memberService.countMembersByClubId(club.getClubId());
            json.put("memeberCount", count);
            //1：是推荐车友会；0：不是推荐车友会
            json.put("isRecommend", 0);

            jsonArray.add(json);
        }

        //组装推荐车友会属性列表
        for (Club club : isRecommendClubs) {
            JSONObject json = new JSONObject();
            json.put("clubId", club.getClubId());
            json.put("name", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getName()) : club.getName());
            json.put("logo", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getLogo()) : club.getLogo());
            json.put("url", systemConfig.getRoot() + "/" + club.getClubUrl() + "/");
            //会员数
            int count = memberService.countMembersByClubId(club.getClubId());
            json.put("memeberCount", count);
            //1：是推荐车友会；0：不是推荐车友会
            json.put("isRecommend", 1);

            jsonArray.add(json);
        }

        //返回车友会列表
        jsonObject.put("data", jsonArray);
        //1:有品牌车友会；0：没有品牌车友会
        jsonObject.put("isBrandClub", isBrandclub);
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION);
    }

    /**
     * 排名即是指“活跃度” 1.默认出当前车系的车友会，按照排名先后露出，最多5个
     * 2.当前车系不足5个的，补当前品牌的车友会，最多5个，车系的优先排前面，品牌的排后面
     * 3.当前品牌不足5个车友会的时候（至少还有1个），下面会出现推荐车友会，缺几个就补几个，最多露出5个
     * 4.推荐车友会的露出，按地区排名最前的来露出，优先城市，然后是省份，最后是全国 5.如果品牌下面一个车友会也没有，则顶部露出创建车友会的按钮
     * 6.下面出该地区下面排名最前的4个地区车友会
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/cms/2.0/club/listTopClubs.do", method = RequestMethod.GET)
    public void listTopClubs2(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //缓存1小时
        WebUtils.setCacheHeader(response, 3600);
        //获取相关参数
        String callback = AppControllerStatic.paramCallback(request);
        int xssEncode = AppControllerStatic.paramXssEncode(request);
        long brandId = AppControllerStatic.paramBrandId(request);
        long seriesId = AppControllerStatic.paramSeriesId(request);
        long provinceId = AppControllerStatic.paramProvinceId(request);
        long cityId = AppControllerStatic.paramCityId(request);
        JSONObject jsonObject = new JSONObject();

        // 非空参数检查
        if (seriesId == 0) {
            AppControllerStatic.printErrorMsg(response, "非法参数seriesId",
                    jsonObject, callback, AppControllerStatic.V2_VERSION_LATEST);
            return;
        }
        if (brandId == 0) {
            AppControllerStatic.printErrorMsg(response, "非法参数brandId",
                    jsonObject, callback, AppControllerStatic.V2_VERSION_LATEST);
            return;
        }

        // 返回的车友会列表
        List<Club> returnClubs = new ArrayList<Club>();
        // 返回推荐车友会列表
        List<Club> isRecommendClubs = new ArrayList<Club>();
        // 根据车系查找车友会，按照排名先后露出，最多5个
        List<Club> seriesClubs = clubService.getListBySeriesId(seriesId, 1,
                DEF_CLUBS_NUM);
        returnClubs.addAll(seriesClubs);
        // 如果根据车系查找的车友会不足5个，查找当前品牌下的车友会
        if (returnClubs.isEmpty() || returnClubs.size() < DEF_CLUBS_NUM) {
            List<Club> brandClubs = clubService
                    .listClubByBrandIdExceptSeriesId(brandId, seriesId, 1,
                    DEF_CLUBS_NUM - returnClubs.size());
            returnClubs.addAll(brandClubs);
        }

        // 1:有品牌车友会；0：没有品牌车友会
        int isBrandclub = 1;

        // 如果品牌没有车友会，显示4个同城车友会
        if (returnClubs.isEmpty()) {
            isBrandclub = 0;
            // 查找当前同城车友会
            List<Club> cityClubs = clubService.getListByCityIdProvinceId(
                    cityId, provinceId, 1, DEF_TONGCHENG_CLUBS_NUM);
            returnClubs.addAll(cityClubs);
            // 查找当前同省车友会
            if (returnClubs.size() < DEF_TONGCHENG_CLUBS_NUM) {
                List<Club> proviceClubs = clubService
                        .listClubByProvinceIdExceptCityId(provinceId, cityId,
                        1, DEF_TONGCHENG_CLUBS_NUM - returnClubs.size());
                returnClubs.addAll(proviceClubs);
            }
            // 查找全国车友会
            if (returnClubs.size() < DEF_TONGCHENG_CLUBS_NUM) {
                List<Club> countryClubs = clubService
                        .getListByCityIdProvinceId(0, 0, 1,
                        DEF_TONGCHENG_CLUBS_NUM - returnClubs.size());
                returnClubs.addAll(countryClubs);
            }

        } else if (returnClubs.size() < DEF_CLUBS_NUM) {// 设置品牌车友会和推荐车友会
            // 查找当前同城车友会
            List<Club> cityClubs = clubService.getListByCityIdProvinceId(
                    cityId, provinceId, 1, DEF_CLUBS_NUM - returnClubs.size());
            isRecommendClubs.addAll(cityClubs);
            // 查找当前同省车友会
            int totalSize = returnClubs.size() + isRecommendClubs.size();
            if (totalSize < DEF_CLUBS_NUM) {
                List<Club> proviceClubs = clubService
                        .listClubByProvinceIdExceptCityId(provinceId, cityId,
                        1, DEF_CLUBS_NUM - totalSize);
                isRecommendClubs.addAll(proviceClubs);
            }
            // 查找全国车友会
            totalSize = returnClubs.size() + isRecommendClubs.size();
            if (totalSize < DEF_CLUBS_NUM) {
                List<Club> countryClubs = clubService
                        .getListByCityIdProvinceId(0, 0, 1, DEF_CLUBS_NUM
                        - totalSize);
                isRecommendClubs.addAll(countryClubs);
            }
        }

        // 组装品牌车友会属性列表
        JSONArray jsonArray = new JSONArray();
        for (Club club : returnClubs) {
            JSONObject json = new JSONObject();
            json.put("clubId", club.getClubId());
            json.put(
                    "name",
                    xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club
                    .getName()) : club.getName());
            json.put(
                    "logo",
                    xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club
                    .getLogo()) : club.getLogo());
            json.put("url", systemConfig.getRoot() + "/" + club.getClubUrl()
                    + "/");
            // 会员数
            int count = memberService.countMembersByClubId(club.getClubId());
            json.put("memeberCount", count);
            // 1：是推荐车友会；0：不是推荐车友会
            json.put("isRecommend", 0);

            jsonArray.add(json);
        }

        // 组装推荐车友会属性列表
        for (Club club : isRecommendClubs) {
            JSONObject json = new JSONObject();
            json.put("clubId", club.getClubId());
            json.put(
                    "name",
                    xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club
                    .getName()) : club.getName());
            json.put(
                    "logo",
                    xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club
                    .getLogo()) : club.getLogo());
            json.put("url", systemConfig.getRoot() + "/" + club.getClubUrl()
                    + "/");
            // 会员数
            int count = memberService.countMembersByClubId(club.getClubId());
            json.put("memeberCount", count);
            // 1：是推荐车友会；0：不是推荐车友会
            json.put("isRecommend", 1);

            jsonArray.add(json);
        }

        // 返回车友会列表
        jsonObject.put("data", jsonArray);
        // 1:有品牌车友会；0：没有品牌车友会
        jsonObject.put("isBrandClub", isBrandclub);
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback,
        		AppControllerStatic.V2_VERSION_LATEST);
    }

    /**
     * 查询上海车展车友会的动态说说
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/cmsapi/1.0/getThemeList.do", method = RequestMethod.GET)
    public void getThemeList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);

        String callback = AppControllerStatic.paramCallback(request);
        int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
        int xssEncode = AppControllerStatic.paramXssEncode(request);

        JSONObject jsonObject = new JSONObject();
        
        Subject subject= subjectService.findByTitle("#上海车展#");
        if(subject == null) {
        	AppControllerStatic.printErrorMsg(response, "没有相关话题", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
        	return;
        }
        
        long subjectId = subject.getSubjectId();
        Pager<DynaInfo> pager = subjectDynaService.pageDynaByShangHai2015(subjectId, pageNo, pageSize, Subject.ALL_DATA);

        JSONArray jsonArray = new JSONArray();
        if (pager != null) {
            if (pager.getResultList() != null) {
                for (DynaInfo info : pager.getResultList()) {
                    JSONObject json = new JSONObject();
                    json.put("content", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(info.getContent()) : info.getContent());
                    json.put("praiseCount", info.getPraiseCount());
                    json.put("replyCount", info.getPostCount());
                    json.put("nickName", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(info.getCreateName()) : info.getCreateName());

                    List<DynaImage> images = info.getImages();
                    List<String> imageUrl = new ArrayList<String>(images.size());
                    for (DynaImage image : images) {
                        if (StringUtils.isBlank(image.getUrl())) {
                            continue;
                        }
                        imageUrl.add(image.getUrl500x500());
                    }
                    if (imageUrl.size() >= 2) {
                        json.put("image1Url", imageUrl.get(0));
                        json.put("image2Url", imageUrl.get(1));
                    } else if (imageUrl.size() == 1) {
                        json.put("image1Url", imageUrl.get(0));
                        json.put("image2Url", "");
                    } else {
                        json.put("image1Url", "");
                        json.put("image2Url", "");
                    }
                    jsonArray.add(json);
                }
            }
            jsonObject.put("themeList", jsonArray);

            jsonObject.put("total", pager.getTotal());
            jsonObject.put("pageNo", pager.getPageNo());
            jsonObject.put("pageSize", pager.getPageSize());
            jsonObject.put("pageCount", pager.getPageCount());

        }
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
    }

    /**
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/cms/1.0/club/listTopClub.do", method = RequestMethod.GET)
    public void listTopClub(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //缓存1小时
        WebUtils.setCacheHeader(response, 3600);
        //获取相关参数
        String callback = AppControllerStatic.paramCallback(request);
        int xssEncode = AppControllerStatic.paramXssEncode(request);
        int num = WebUtils.paramInt(request, "num", 10);
        if (num > 20) {
            num = 20;
        }
        List<ClubStat> list = statService.listClubByRankPetrol(num);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for (ClubStat cs : list) {
            Club c = cs.getClub();
            JSONObject o = new JSONObject();
            o.put("logo", c.getLogo());
            o.put("clubId", c.getClubId());
            o.put("logo150x150", c.getLogo150x150());
            o.put("name", EncodeUtils.encodeForHTML(c.getName(), xssEncode == 1));
            o.put("levelId", c.getLevelId());
            o.put("url", c.getClubUrl());
            o.put("clubUrl", systemConfig.getRoot() + "/" + c.getClubUrl() + "/");
            o.put("rankPetrol", cs.getRankPetrol());
            o.put("niceRankPetrol",
                    cs.getRankPetrol() > 10000
                    ? (cs.getRankPetrol() / 100 + 5) / 10 / 10.0 + "万" : cs.getRankPetrol());
            jsonArray.add(o);
        }
        jsonObject.put("clubList", jsonArray);
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     *
     * 获取车友会列表接口(WAP汽车网首页调用http://m.pcauto.com.cn 注:未登录时调用)
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/cms/1.0/club/getClubByRegionId.do", method = RequestMethod.GET)
    public void getClubByRegionId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        WebUtils.setEncoding(req, resp);
        String callback = WebUtils.param(req, "callback", "");
        long cityId = WebUtils.paramInt(req, "cityId", 0);
        long provinceId = WebUtils.paramInt(req, "provinceId", 0);
        String clubName = WebUtils.paramTrim(req, "clubName", "");
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        long brandId = WebUtils.paramInt(req, "brand", 0);
        int pageNo = AppControllerStatic.paramPageNo(req);
        int pageSize = AppControllerStatic.paramPageSize(req);
        boolean isXSS = true;
        Pager<Club> pager = clubService.pageClubByPlaceId(cityId, 0, provinceId, brandId, null, clubId, clubName, pageNo, pageSize, 0);
        JSONObject json = new JSONObject();
        if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            JSONArray jsonArray = new JSONArray();
            for (Club club : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("clubId", club.getClubId());
                jsonObject.put("name", EncodeUtils.encodeForHTML(club.getName(), isXSS));
                jsonObject.put("logo", EncodeUtils.encodeForHTML(club.getLogo(), isXSS));
                jsonObject.put("memberSum", club.getMemberNum());
                jsonObject.put("totalPetrol", club.getTotalPetrol());
                jsonObject.put("level", club.getLevelId());
                jsonObject.put("clubStatus", club.getStatus());
                jsonObject.put("brandId", club.getBrandId());
                jsonObject.put("seriesName", EncodeUtils.encodeForHTML(club.getSeriesName(), isXSS));
                jsonObject.put("brandName", EncodeUtils.encodeForHTML(club.getBrandName(), isXSS));
                jsonObject.put("provinceName", EncodeUtils.encodeForHTML(club.getProvinceName(), isXSS));
                jsonObject.put("cityName", EncodeUtils.encodeForHTML(club.getCityName(), isXSS));
                jsonObject.put("clubUrl", club.getClubUrl());
                jsonArray.add(jsonObject);
            }
            AppUtils.setSuccessCode(json);
            json.put("data", jsonArray);
            json.put("total", pager.getTotal());
            json.put("pageNo", pager.getPageNo());
            json.put("pageCount", pager.getPageCount());
            json.put("pageSize", pager.getPageSize());
        } else {
            json.put("data", new JSONArray());
            AppUtils.setSuccessCode(json);
        }
        AppControllerStatic.printSuccessMsg(resp, json, callback, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 根据动态ID，获取动态赞数，评论数
     * 动态ID可以多个，使用“，”连接起来
     * 
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/cms/1.0/dyna/getPraisePostCountByIds.do", method = RequestMethod.GET)
    public void getPraisePostCountByIds(HttpServletRequest request, HttpServletResponse response){
        WebUtils.setEncoding(request, response);
        //缓存1小时
        WebUtils.setCacheHeader(response, 3600);
        
        String callback = WebUtils.param(request, "callback", "");
        String[] dynaInfoIds = WebUtils.param(request, "dynaInfoIds", "").split(",");
        
        JSONObject jsonObject = new JSONObject();
        
        //将动态ID转变为长整形
        List<Long> ids = new ArrayList<Long>(dynaInfoIds.length);
        for(String dynaInfoIdString : dynaInfoIds){
        	try {
        		ids.add(Long.parseLong(dynaInfoIdString));
        	}catch(NumberFormatException exception) {
        		continue;
        	}
        }
        
        JSONArray jsonArray = new JSONArray();
        //获取动态的赞数，评论数
        for(Long dynaInfoId : ids) {
        	DynaIndex dynaIndex = dynaIndexService.findDynaIndex(dynaInfoId);
        	if(dynaIndex == null) {
        		continue;
        	}
        	DynaInfo dynaInfo = dynaService.findDynaInfoById(dynaInfoId, dynaIndex.getCreateDate());
        	if(dynaInfo == null) {
        		continue;
        	}
        	
        	JSONObject json = new JSONObject();
        	json.put("dynaInfoId", dynaInfoId);
        	json.put("praiseCount", dynaInfo.getPraiseCount());
        	json.put("postCount", dynaInfo.getPostCount());
        	
        	jsonArray.add(json);
        }
        
        jsonObject.put("dynaList", jsonArray);
        
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
        
    }
}
